package com.itheima.interceptors;

import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
//import com.itheima.utils.JedisUtil;
import com.itheima.utils.JedisUtl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private JedisUtl jedisUtl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //随机码
        String token = request.getHeader("token");
        //没有携带token
        if(token==null){
          noLogin(response);
            return false;
        }
        //得到的是会员json信息
        String usertoken = jedisUtl.get(token);
        Member member = JSON.parseObject(usertoken, Member.class);
        if(member!=null){

            return true;
        }else{
            noLogin(response);
            return false;
        }

    }

    private void noLogin(HttpServletResponse response) throws IOException {
        Result result = new Result(false,"没有登录",401);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(result));
        writer.close();
    }
}
